package com.example.librarymanagementsystembackend.usermanagement.controller;

import com.example.librarymanagementsystembackend.usermanagement.entity.LoginInfo;
import com.example.librarymanagementsystembackend.usermanagement.entity.LoginResponse;
import com.example.librarymanagementsystembackend.usermanagement.entity.User;
import com.example.librarymanagementsystembackend.usermanagement.service.UserService;
import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.librarymanagementsystembackend.utils.JwtUtil;

@RestController
public class UserAuthenticationController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public LoginResponse login(@RequestBody LoginInfo loginInfo) {
        if (loginInfo == null) {
            throw new InvalidRequestException("无效请求体");
        }
        User user = userService.login(loginInfo);
        if (user != null) {
            String token = JwtUtil.generateToken(user.getId().toString());// 返回Token
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setUserId(Integer.parseInt(JwtUtil.getValidTokenSubject(token)));
            loginResponse.setToken(token);
            return loginResponse;
        }
        throw new InvalidRequestException("用户名或密码错误");
    }
}
